package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.*;
import com.itheima.service.MemberService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@RestController
@RequestMapping("/member")
public class MemberController {
    @Reference
    private MemberService memberService;

    /**
     * 检查项分页查询
     *
     * @param queryPageBean
     * @return
     */
    @RequestMapping("/selectAllByName")
    public PageResult selectAllByName(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = memberService.pageQuery(queryPageBean);
        return pageResult;
    }

    /**
     * 添加会员信息
     *
     * @param member
     * @return
     */
    @RequestMapping("/add")
    public Result add(@RequestBody Member member) {
        try {
            memberService.add(member);
        } catch (Exception e) {
            e.printStackTrace();
            //服务调用失败
            return new Result(false, MessageConstant.ADD_MEMBER_FAIL);
        }
        return new Result(true, MessageConstant.ADD_MEMBER_SUCCESS);
    }

    /**
     * 编辑会员信息
     *
     * @param member
     * @return
     */
    @RequestMapping("/updateOne")
    public Result updateOne(@RequestBody Member member) {
        try {
            memberService.edit(member);
        } catch (Exception e) {
            e.printStackTrace();
            //服务调用失败
            return new Result(false, MessageConstant.EDIT_MEMBER_FAIL);
        }
        return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS);
    }

    @RequestMapping("/deleteById")
    public Result deleteById(Integer id) {
        try {
            memberService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            //服务调用失败
            return new Result(false, MessageConstant.DELETE_MEMBER_FAIL);
        }
        return new Result(true, MessageConstant.DELETE_MEMBER_SUCCESS);
    }



    /**
     * 批量导出excel
     *
     * @param
     * @return
     */
    @RequestMapping("/exportMember")
    public Result exportMember(HttpServletRequest request, HttpServletResponse response, Integer[] memberIds) {
        try {
            //读取模板文件,把查询出的数据写入模板文件中
            //动态获得文件路径
            String filePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "MemberMessage.xlsx";
            //基于模板文件在内存中创建一个文件
            XSSFWorkbook file = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            //获取第一个sheet
            XSSFSheet sheet = file.getSheetAt(0);
            for (int i = 0; i < memberIds.length; i++) {
                //根据id获取数据,把查询出的数据写入模板文件中
                Usermanage usermanage = memberService.findById(Integer.valueOf(memberIds[i]));
                //根据id查询地址
                List<String> addresses = memberService.findAddress(memberIds[i]);
                String address = "";
                for (int j = 0; j < addresses.size(); j++) {
                    if (j==(addresses.size()-1)){
                        //说明最后一个
                        address += addresses.get(j);
                    }else {
                        address += addresses.get(j)+",";
                    }
                }
                //根据id查询套餐
                List<Setmeal> setmeals = memberService.findSetmealNameByMemberId(memberIds[i]);
                String setmealStr = "";
                String checkGroupStr= "";
                String checkItemStr= "";
                for (Setmeal setmeal : setmeals) {
                    String name = setmeal.getName();
                    setmealStr += " "+name;
                    List<CheckGroup> checkGroups = setmeal.getCheckGroups();
                    for (CheckGroup checkGroup : checkGroups) {
                        //获取检查组
                        checkGroupStr += " "+checkGroup.getName();
                        for (CheckItem checkItem : checkGroup.getCheckItems()) {
                            //获取检查项
                            checkItemStr += " "+ checkItem.getName();
                        }
                    }
                }
                //向单元格中填充数据
                XSSFRow row = sheet.createRow(i + 3);
                if (usermanage.getName() != null) {
                    row.createCell(0).setCellValue(usermanage.getName());//姓名
                }
                if (usermanage.getSex() != null) {
                    row.createCell(1).setCellValue(usermanage.getSex());//性别
                }
                if (usermanage.getPhoneNumber() != null) {
                    row.createCell(2).setCellValue(usermanage.getPhoneNumber());//手机号
                }
                if (address!=null&&address.length()>0){
                    row.createCell(3).setCellValue(address);
                }
                if (setmealStr!=null&&setmealStr.length()>0){
                    row.createCell(4).setCellValue(setmealStr);
                }
                if (checkGroupStr!=null&&checkGroupStr.length()>0){
                    row.createCell(5).setCellValue(checkGroupStr);
                }
                if (checkItemStr!=null&&checkItemStr.length()>0){
                    row.createCell(6).setCellValue(checkItemStr);
                }
            }
            //使用输出流进行表格下载,基于浏览器作为客户端下载
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");//指定以附件形式进行下载
            file.write(out);

            out.flush();
            out.close();
            file.close();
            return null;
        }catch (Exception e){
            return new Result(false,"导出失败");
        }
    }
}